import asyncio

import requests
from mitmproxy.tools.dump import DumpMaster
from mitmproxy.options import Options
from mitmproxy import http


# 需要忽略的域名（正则表达式字符串）
IGNORED_DOMAINS = [r".*baidu\.com.*", r".*firefox\.com.*",r".*bdimg\.com.*",r".*github\.com.*",r".*githubusercontent\.com.*",
                   r".*googleapis\.com.*",r".*google\.com.*",r".*bdstatic\.com.*",r".*mozilla\.org.*",r".*mozilla\.com.*",
                   r".*qq\.com,*",r".*openai\.com.*"]

patter_login_username = 'aaaaaa'
patter_login_password = 'bbbbbb'
MD5_patter_login_password = '875f26fdb1cecf20ceb4ca028263dec6'
Base64_patter_login_password = 'YmJiYmJi'

# 任务生成 API 地址
TASK_API_URL = "http://100.127.59.254:4646/create_task"


class TrafficLogger:
    def request(self, flow: http.HTTPFlow):
        """请求拦截逻辑"""
        request_data_post = flow.request.get_text()
        request_data_get = flow.request.path

        if patter_login_username in request_data_post:
            self.create_task(flow, request_data_post)
        elif patter_login_username in request_data_get:
            self.create_task(flow, request_data_get)

    def detect_password_type(self, data: str) -> str:
        """判断密码是哪种编码"""
        if MD5_patter_login_password in data.lower():
            return "md5"
        elif Base64_patter_login_password in data:
            return "base64"
        elif patter_login_password in data:
            return "plain"
        else:
            return "unknown"

    def create_task(self, flow: http.HTTPFlow, data: str):
        """创建爆破任务，仅识别密码类型明确时发送"""
        password_type = self.detect_password_type(data)

        if password_type == "unknown":
            print("跳过未知编码的密码请求:", flow.request.url,"编码数据:", data)
            return  # 不发送请求

        task_data = {
            "url": flow.request.url,
            "method": flow.request.method,
            "headers": dict(flow.request.headers),
            "body": flow.request.get_text(),
            "password_type": password_type  # 明确传递密码类型
        }

        try:
            response = requests.post(TASK_API_URL, json=task_data, timeout=5)
            if response.status_code == 201:
                print("任务创建成功:", response.json())
            else:
                print("任务创建失败:", response.status_code, response.text)
        except requests.RequestException as e:
            print("任务请求异常:", e)

class ProxyRunner(DumpMaster):
    def __init__(self, options):
        super().__init__(options)
        self.addons.add(TrafficLogger())  # 注册插件

async def start_proxy():
    options = Options(
        listen_host="0.0.0.0",
        listen_port=8080,
        ignore_hosts=IGNORED_DOMAINS,
        ssl_insecure=True  # 允许代理忽略 SSL 证书验证失败
    )
    proxy = ProxyRunner(options)
    print(f"代理服务器启动，监听端口: 8080，忽略域名: {', '.join(IGNORED_DOMAINS)}")

    try:
        await proxy.run()
    except KeyboardInterrupt:
        print("代理服务器已停止")

if __name__ == "__main__":
    asyncio.run(start_proxy())  # 通过 asyncio 运行代理
